package com.isunland.managesystem.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.RequestManager;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.Login;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 自动登录
 */
public class SplashFragment extends Fragment {
  protected static final String TAG = "SplashFragment";
  private BaseVolleyActivity mActivity;
  private CurrentUser mUser;

  @Override public void onCreate(Bundle savedInstanceState) {
    mActivity = (BaseVolleyActivity) getActivity();
    mUser = CurrentUser.newInstance(getActivity());
    // String jsonMapStr =
    // "{\"age\":null,\"id\":\"tt_2009_4\",\"name\":\"tt_2009_4\",\"province\":\"上海\",\"sex\":\"男\"}";
    // HashMap<String ,String> map = MyUtils.toHashMap(jsonMapStr);
    // for(String key:map.keySet()){
    // System.out.println(key+":"+map.get(key));
    // //System.out.println(map.size());
    // }
    if (mUser.isLogin()) {
      volleyPostLogin();
    } else {
      startActivityLogin();
    }

    super.onCreate(savedInstanceState);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_splash, container, false);
  }

  private void startActivityLogin() {
    Toast.makeText(getActivity(), R.string.auto_login_failure, Toast.LENGTH_SHORT).show();
    Intent i = new Intent(getActivity(), LoginActivity.class);
    startActivity(i);
    getActivity().finish();
  }

  private void volleyPostLogin() {

    if (!MyUtils.isNetLink(getActivity())) {
      Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_SHORT).show();
      startActivityLogin();
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LOGIN);

    HashMap<String, String> params = new HashMap<>();
    params.put("username", mUser.getName());
    params.put("password", mUser.getPassword());
    // boolean
    // hasPermission=mActivity.checkPermission(Manifest.permission.READ_PHONE_STATE);

    //登陆是传递
    String id = MyUtils.getDeviceId(getActivity());
    params.put("phoneIdentifyNumber", id);

    LogUtil.i(TAG, "url=" + ApiConst.getAbsoluteUrl(ApiConst.URL_LOGIN));
    LogUtil.i(TAG, "params=" + params.toString());
    // Bugtags.log("LoginParams="+params);

    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onResponse(String arg0) {
        handleResponse(arg0);
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        //handleResponse(arg0);

      }

      @Override public void onVolleyError(VolleyError arg0) {

        startActivityLogin();
      }
    });
  }

  //public Response.ErrorListener errorListener() {
  //	return new Response.ErrorListener() {
  //		@Override
  //		public void onErrorResponse(VolleyError error) {
  //			LogUtil.e(TAG, "volleyError=" + error.toString(), error);
  //			startActivityLogin();
  //
  //		}
  //	};
  //}

  private void handleResponse(String response) {
    SharedPreferencesUtil.setString(getActivity(), SharedPreferencesUtil.COOKIE,
        RequestManager.getCookie());
    LogUtil.i(TAG, "response=" + response);

    try {

      Thread.sleep(1000);

      Login login = new Gson().fromJson(response, Login.class);

      if ((login == null) || (login.isSuccess() == null) || (!login.isSuccess())) {
        startActivityLogin();
        return;
      }

      //mUser.update();
      //mUser.setMobile(mBtnLogin.getMobile());
      //mUser.setMemberName(mBtnLogin.getMemberName());
      //mUser.setKeypositionName(mBtnLogin.getKeypositionName());
      //mUser.setEmail(mBtnLogin.getEmail());
      //mUser.setBirthDate(mBtnLogin.getBirthDate());
      //mUser.setDeptName(mBtnLogin.getDeptName());
      //mUser.setPhoneIdentifyNumber(mBtnLogin.getPhoneIdentifyNumber());
      //mUser.setDeptCode(mBtnLogin.getDeptCode());
      // mUser.toString();

      // Intent i = new Intent(getActivity(), FunctionMenuActivity.class);
      //登陆成功
      mUser.update(mUser.getName(), mUser.getPassword(), login.getUserName(),
          login.getUserId() + "", login.getMemberCode(), login.getJobNo(), login.getPicture(),
          login.getPhoneIdentifyNumber(), login.getDeptCode(), login.getPushClientId(),
          login.getDeptName(), login.getKeypositionName(), login.getEmail(), login.getMemberName(),
          login.getMobile(), login.getManageOrgCode(), login.getManageOrgName(), true);

      // 菜单 导航界面
      //            Intent i = new Intent(getActivity(), GuideMenuActivity.class);
      //			startActivity(i);
      //			getActivity().finish();
      if ((MyUtils.isDevelopMode(mActivity)) && (mUser != null)) {
        MyUtils.addPath(ApiConst.sUrlMain);
        MyUtils.addUser(mUser.getName(), mUser.getPassword());
      }
      // 菜单 导航界面
      Intent i = new Intent(getActivity(), GuideMenuNewActivity.class);
      startActivity(i);
      getActivity().finish();
    } catch (Exception e) {
      LogUtil.e(TAG, "errorMsg", e);
      startActivityLogin();
    }
  }
}
